﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;


namespace HelloMVC.Model
{
    #region custom attribute
    public interface ICustomValue
    {
        void AddToDirectory(IDictionary<string, object> values);
    }

    /// <summary>
    /// autocomplete attribute class [required]
    /// Name: autocomplete name [required]
    /// Cotroller: request controller [requierd]
    /// Servoce: request action [optional, default to "AutocompleteService"]
    /// Area: request area [optional, default to current area]
    /// </summary>
    public class AutocompleteAttribute : Attribute, ICustomValue
    {
        public String Name { get; set; }
        public String Area { get; set; }
        public String Controller { get; set; }
        public String Service { get; set; }
        public String DependentEleId { get; set; }
        private String Url
        {
            get
            {
                Service = String.IsNullOrWhiteSpace(Service) ? "AutocompleteService" : Service;
                var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
                return urlHelper.Action(Service, Controller) + "?name=" + Name;
            }
        }

        public void AddToDirectory(IDictionary<string, object> values)
        {
            values.Add("auto-service", Url);
            values.Add("auto-rel", DependentEleId);
        }
    }

    public class MyMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
        {
            var _default = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
            var customs = attributes.Where(x => x is AutocompleteAttribute);
            foreach (ICustomValue custom in customs)
            {
                custom.AddToDirectory(_default.AdditionalValues);
            }
            return _default;
        }
    }

    #endregion
}
